library(tidyverse)

set.seed(20250416)

dataRaw = read_delim("rankings.txt")

dataLong = dataRaw %>% 
  group_by(question) %>% 
  mutate(score = (max(rank, na.rm = T) - rank) + 1)

plotData = dataLong %>% 
  group_by(question, answer) %>% 
  summarise(score = sum(score, na.rm = T))

bootTable = tibble(sample = 1:1000) %>% 
  mutate(boot = map(sample,
                    ~ dataLong %>% 
                      sample_frac(replace = T) %>%
                      group_by(question, answer) %>% 
                      summarise(score = sum(score, na.rm = T),
                                .groups = "drop"))) %>% 
  unnest(boot)

bootSummary = bootTable %>%
  group_by(question, answer) %>%
  summarise(mean_score = mean(score),
            ci_lower = quantile(score, 0.025),
            ci_upper = quantile(score, 0.975),
            .groups = "drop")

plotTable = bootSummary %>% 
  group_by(question) %>% 
  nest %>% 
  mutate(plot = map2(data,
                     question,
                     ~ .x %>% 
                       ggplot()+
                       geom_point(aes(reorder(answer, 
                                              mean_score,
                                              decreasing = T), 
                                      mean_score),
                                  position = position_dodge2(width = .1))+
                       geom_errorbar(aes(answer, 
                                         ymin = ci_lower, 
                                         ymax = ci_upper),
                                     position = position_dodge2(width = .1),
                                     width = .1) +
                       scale_x_discrete(name = NULL)+
                       scale_y_continuous(name = "Borda count")+
                       ggtitle(.y)+
                       theme_bw()+
                       theme(axis.text.x = element_text(angle = 320,
                                                        hjust = 0))))

cairo_pdf(filename = "borda-counts.pdf",
          onefile = T,
          width = 6,
          height = 4)
plotTable %>%
  pluck("plot")
dev.off()
